using UnityEngine;

namespace Function.SkillEditor.Runtime
{
    [ExecuteInEditMode]
    public class SceneGridDrawer : MonoBehaviour
    {
        public Color mainColor = Color.red;
        public Color subColor = 0.5f * Color.blue;
        public float interval = 1.0f; // 网格单位间隔
        public int subCounts = 5;

        public int halfSize = 10;

        private Material lineMatMain;
        private Material lineMatSub;

        void Start()
        {
            lineMatMain = new Material(Shader.Find("SCore/PureColor"));
            lineMatMain.SetColor("_Color", mainColor);

            lineMatSub = new Material(Shader.Find("SCore/PureColor"));
            lineMatSub.SetColor("_Color", subColor);
        }

        void OnRenderObject()
        {
            // x方向
            for (int i = -halfSize; i <= halfSize; ++i)
            {
                bool isMainLine = (i % 5 == 0);
                DrawLine(new Vector3(-halfSize, 0, i), new Vector3(halfSize, 0, i), isMainLine);
            }

            // z方向
            for (int i = -halfSize; i <= halfSize; ++i)
            {
                bool isMainLine = (i % 5 == 0);
                DrawLine(new Vector3(i, 0, -halfSize), new Vector3(i, 0, halfSize), isMainLine);
            }
        }


        void DrawLine(Vector3 pointA, Vector3 pointB, bool main)
        {
            //GL.PushMatrix();
            GL.MultMatrix(Matrix4x4.identity);
            Material mat = main ? lineMatMain : lineMatSub;
            GL.Begin(GL.LINES);
            mat.SetPass(0);
            GL.Vertex3(pointA.x, pointA.y, pointA.z);
            GL.Vertex3(pointB.x, pointB.y, pointB.z);
            GL.End();
            //GL.PopMatrix();
        }
    }
}